import React = require("react");
import { PageProps } from "maishu-chitu-react";
import * as wuzhui from "maishu-wuzhui";
import * as wz from "maishu-wuzhui-helper";
import { ActivityService } from "services/activity";
import { ItemDialog } from "controls/item-dialog";
import { dataSources } from "services/dataSources";
import site from "site";
import { FormValidator, rules as r } from "maishu-dilu";
import "bootstrap-datepicker";
import { formatDate } from "mobile/site";
import { customDataField } from "fields/custom-data-field";
import ReactDOM = require("react-dom");
import { buttonOnClick } from "maishu-ui-toolkit";


export default class ActivitiesPage extends React.Component<PageProps, {}>{
    private dataSource: wuzhui.DataSource<any>;
    // private itemEditor: GridViewItemPopupEditor;
    activity: ActivityService;
    activityDialog: ActivityDialog;
    activityTable: any;

    constructor(props) {
        super(props);

        this.state = {};
        this.activity = this.props.createService(ActivityService);
    }
    componentDidMount() {
        let it = this;
        new wuzhui.GridView({
            element: this.activityTable,
            dataSource: dataSources.activity,
            columns: [
                wz.boundField({ dataField: 'Name', headerText: '活动名称' }),
                wz.boundField({ dataField: 'BeginDate', headerText: '开始日期', dataFormatString: '{d}' }),
                wz.boundField({ dataField: 'EndDate', headerText: '结束日期', dataFormatString: '{d}' }),
                customDataField<PromotionActivity>({
                    headerText: "操作",
                    render(dataItem, element) {
                        ReactDOM.render(<div className="text-center">
                            <button className="btn btn-minier btn-info"
                                onClick={() => it.props.app.redirect(`shopping/promotion/activityEdit`, { id: dataItem.Id })}>
                                <i className="icon-cog" />
                                <span>设置</span>
                            </button>
                            <button className="btn btn-minier btn-info" title="点击编辑"
                                onClick={() => {
                                    it.activityDialog.show(dataItem, "编辑活动", (item) => {
                                        dataSources.activity.update(item);
                                    });
                                }} >
                                <i className="icon-pencil" />
                            </button>
                            <button className="btn btn-minier btn-danger" title="点击删除"
                                ref={e => {
                                    if (!e) return;
                                    buttonOnClick(e, () => {
                                        return dataSources.activity.delete(dataItem);
                                    }, { confirm: `确定删除 '${dataItem.Name}' 吗` })
                                }}>
                                <i className="icon-trash" />
                            </button>
                        </div>, element);
                    }
                })

            ]
        })

        dataSources.activity.select();
    }
    newActivity() {
        // this.itemEditor.show();
        this.activityDialog.show({} as any, "添加活动", (item) => {
            dataSources.activity.insert(item);
        });
    }
    saveDataItem(dataItem: Promotion) {
        if (dataItem.Id)
            return this.dataSource.update(dataItem);

        return this.dataSource.insert(dataItem);
    }
    render() {
        return (
            <div>
                <div className="tabbable">
                    <ul className="nav nav-tabs">
                        <li className="pull-right">
                            <button className="btn btn-primary btn-sm pull-right"
                                ref={e => {
                                    if (!e) return;
                                    e.onclick = () => this.newActivity();
                                }}>
                                <i className="icon-plus" />
                                <span>添加</span>
                            </button>
                        </li>
                    </ul>
                </div>
                <table className={site.style.tableClassName} ref={e => this.activityTable = e || this.activityTable}></table>
                {/* <wz.GridViewItemPopupEditor name="活动"
                    ref={(e) => {
                        if (!e) return;
                        this.itemEditor = e;
                        // e.validator = new FormValidator(e.element, {
                        //     BeginDate: { rules: ['required'] },
                        //     EndDate: { rules: ['required'] }
                        // })
                        let beginDateElement = e.element.querySelector('[name="BeginDate"]') as HTMLInputElement;
                        let endDateElement = e.element.querySelector('[name="EndDate"]') as HTMLInputElement;
                        e.validator = new FormValidator(e.element,
                            { name: "BeginDate", rules: [rules.required()] },
                            { name: "EndDate", rules: [rules.required()] },
                        )
                    }}
                    saveDataItem={(dataItem) => {
                        if (dataItem.Id)
                            return this.dataSource.update(dataItem);

                        return this.dataSource.insert(dataItem);
                    }}>
                    <div className="form-group">
                        <label className="control-label col-sm-2">活动名称</label>
                        <div className="col-sm-10">
                            <input name="Name" className="form-control" autoFocus={true} placeholder="请输入活动的名称" />
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="control-label col-sm-2">开始日期</label>
                        <div className="col-sm-10">
                            <input name="BeginDate" className="form-control" autoFocus={true} placeholder="请输入活动的开始日期" />
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="control-label col-sm-2">结束日期</label>
                        <div className="col-sm-10">
                            <input name="EndDate" className="form-control" autoFocus={true} placeholder="请输入活动的结束日期" />
                        </div>
                    </div>
                </wz.GridViewItemPopupEditor> */}
                <ActivityDialog ref={e => this.activityDialog = e || this.activityDialog} />
            </div>
        );
    }
}



class ActivityDialog extends ItemDialog<{}, PromotionActivity> {

    private readonly NAME = "Name";
    private readonly BEGIN_DATE = "BeginDate";
    private readonly END_DATE = "EndDate";

    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.validator = new FormValidator(this.element,
            { name: this.NAME, rules: [r.required("请输入活动的名称")] },
            { name: this.BEGIN_DATE, rules: [r.required("请输入活动的开始日期")] },
            { name: this.END_DATE, rules: [r.required("请输入活动的结束日期")] }
        );

        let beginDateElement: HTMLInputElement = document.querySelector(`[name="${this.BEGIN_DATE}"]`);
        let endDateElement: HTMLInputElement = document.querySelector(`[name="${this.END_DATE}"]`);

        $([beginDateElement, endDateElement]).datepicker({
            format: "yyyy-mm-dd",
            language: "zh-CN",
            autoclose: true,
        } as any).on("hide", (e) => {
            let target = e.target as HTMLInputElement;
            let item = this.state.item;
            item[target.name] = new Date(target.value);
        });

    }

    render() {
        let { item } = this.state;
        
        return <>
            <div className="form-group clearfix">
                <label className="control-label col-sm-2">活动名称</label>
                <div className="col-sm-10">
                    <input name={this.NAME} className="form-control" autoFocus={true} placeholder="请输入活动的名称"
                        value={item.Name || ""}
                        onChange={e => {
                            item.Name = e.target.value;
                            this.setState({ item });
                        }} />
                </div>
            </div>
            <div className="form-group clearfix">
                <label className="control-label col-sm-2">开始日期</label>
                <div className="col-sm-10">
                    <input name={this.BEGIN_DATE} className="form-control" autoFocus={true} placeholder="请输入活动的开始日期"
                        value={item.BeginDate ? formatDate(item.BeginDate) : ""}
                        onChange={e => {
                            item.BeginDate = new Date(e.target.value);
                            this.setState({ item })
                        }} />
                </div>
            </div>
            <div className="form-group clearfix">
                <label className="control-label col-sm-2">结束日期</label>
                <div className="col-sm-10">
                    <input name={this.END_DATE} className="form-control" autoFocus={true} placeholder="请输入活动的结束日期"
                        value={item.EndDate ? formatDate(item.EndDate) : ""}
                        onChange={e => {
                            item.EndDate = new Date(e.target.value);
                            this.setState({ item });
                        }} />
                </div>
            </div>
        </>
    }
}